

export function useUpgrade(cpe) {
  const loading = useLoading()
  const upgradeVisible = ref(false)
  const currentCpe = ref(cpe)
  const upgradeType = ref('')

  function openUpgrade(type, row) {
    if (row)
      currentCpe.value = row
    upgradeType.value = type
    upgradeVisible.value = true
  }

  // 是否可以升级
  function upgradeDisabled(upgradeType = 'agent') {
    const { status, agentUpgrade, systemUpgrade, bpFlowUpgrade } = currentCpe.value
    const keyMap = {
      agent: agentUpgrade,
      system: systemUpgrade,
      bpflow: bpFlowUpgrade,
    }
    const upgrade = keyMap[upgradeType]
    // 是离线或者有不需要升级标签
    return status === 'Offline' || upgrade === 'NoNeed'
  }

  async function upgradeDone({ versionUuid }) {
    const params = {
      cpeUuid: currentCpe.value.uuid,
      cpeSystemUuid: '',
      cpeAgentUuid: '',
      bpFlowVersionUuid: '',
    }
    let fnKey = ''
    if (upgradeType.value === 'agent') {
      fnKey = 'UpgradeCpeAgent'
      params.cpeAgentUuid = versionUuid
    }
    else if (upgradeType.value === 'system') {
      fnKey = 'UpgradeCpeSystem'
      params.cpeSystemUuid = versionUuid
    }
    else {
      fnKey = 'UpgradeCpeBpFlow'
      params.bpFlowVersionUuid = versionUuid
    }
    loading.open()
    const { success } = await useRequest(fnKey, params)
    loading.close()

    if (success) {
      ElNotification({
        type: 'success',
        message: '升级成功',
      })
    }
    upgradeVisible.value = false
  }
  return {
    upgradeVisible,
    upgradeType,
    openUpgrade,
    upgradeDisabled,
    upgradeDone,
  }
}
